package com.whj.servicemap.remote;

import com.whj.internalcommon.constant.AMapConfigConstant;
import com.whj.internalcommon.constant.CommonStatusEnum;
import com.whj.internalcommon.dto.ResponseResult;
import com.whj.internalcommon.response.TerminalResponse;
import com.whj.internalcommon.response.TrsearchResponse;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: wanghaijun
 * @Date: 2023/1/16 - 01 - 16 - 17:29 
 * @Description: com.whj.servicemap.remote
 */

@Service
@Slf4j
public class TerminalClient {

    @Value("${amap.key}")
    private String amapKey;

    @Value("${amap.sid}")
    private String amapSid;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 获取终端设备id
     *
     * @param name
     * @param desc 车辆的id
     * @return
     */
    public ResponseResult<TerminalResponse> add(String name, String desc) {

        //?key=9edd7a0c343d993fc971ad2afda94dd5&sid=869338&name=车辆1
        StringBuilder url = new StringBuilder();
        url.append(AMapConfigConstant.TERMINAL_ADD_URL);
        url.append("?");
        url.append("key=" + amapKey);
        url.append("&");
        url.append("sid=" + amapSid);
        url.append("&");
        url.append("name=" + name);
        url.append("&");
        url.append("desc=" + desc);
        log.info("创建终端的请求：" + url.toString());

        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        log.info("创建终端的响应：" + forEntity.getBody());
        /**
         * {
         *     "data": {
         *         "name": "车辆5",
         *         "tid": 623356183,
         *         "sid": 869338
         *     },
         *     "errcode": 10000,
         *     "errdetail": null,
         *     "errmsg": "OK"
         * }
         */
        String body = forEntity.getBody();
        JSONObject result = JSONObject.fromObject(body);
        JSONObject data = result.getJSONObject("data");
        String tid = data.getString("tid");
        TerminalResponse terminalResponse = new TerminalResponse();
        terminalResponse.setTid(tid);
        return ResponseResult.success(terminalResponse);
    }

    /**
     * 根据圆心半径搜索设备，并返回实时位置 调用高德api
     *
     * @param center
     * @param radius
     * @return
     */
    public ResponseResult<List<TerminalResponse>> aroundSearch(String center, Integer radius) {

        //center=39.98,116.38&radius=1000
        StringBuilder url = new StringBuilder();
        url.append(AMapConfigConstant.TERMINAL_AROUNDSEARCH_URL);
        url.append("?");
        url.append("key=" + amapKey);
        url.append("&");
        url.append("sid=" + amapSid);
        url.append("&");
        url.append("center=" + center);
        url.append("&");
        url.append("radius=" + radius);
        log.info("周边搜索终端的请求：" + url.toString());
        ResponseEntity<String> forEntity = restTemplate.postForEntity(url.toString(), null, String.class);
        log.info("周边搜索终端的响应" + forEntity.getBody());

        //解析终端搜索结果 获取 tid 和desc
        /**
         * {
         *   "data": {
         *     "count": 1,
         *     "results": [
         *       {
         *         "createtime": 1674804825225,
         *         "desc": "1594231277809336325",
         *         "locatetime": 1674197512547,
         *         "location": {
         *           "accuracy": 550.0,
         *           "direction": 511.0,
         *           "distance": 0,
         *           "height": null,
         *           "latitude": 39.98,
         *           "longitude": 116.38,
         *           "speed": 255.0,
         *           "trackProps": null
         *         },
         *         "name": "川A76554",
         *         "props": null,
         *         "tid": 626492999
         *       }
         *     ]
         *   },
         *   "errcode": 10000,
         *   "errdetail": null,
         *   "errmsg": "OK"
         * }
         */

        List<TerminalResponse> terminalResponses = new ArrayList<>();
        JSONObject result = JSONObject.fromObject(forEntity.getBody());
        JSONObject data = result.getJSONObject("data");
        JSONArray results = data.getJSONArray("results");
        for (int i = 0; i < results.size(); i++) {
            TerminalResponse terminalResponse = new TerminalResponse();
            JSONObject jsonObject = results.getJSONObject(i);
            String desc = jsonObject.getString("desc");
            Long carId = Long.parseLong(desc);
            //丢失精度
            //Long carId = jsonObject.getLong("desc");
            String tid = jsonObject.getString("tid");

            JSONObject location = jsonObject.getJSONObject("location");
            String latitude = location.getString("latitude");
            String longitude = location.getString("longitude");

            terminalResponse.setTid(tid);
            terminalResponse.setCarId(carId);
            terminalResponse.setLatitude(latitude);
            terminalResponse.setLongitude(longitude);
            terminalResponses.add(terminalResponse);
        }

        return ResponseResult.success(terminalResponses);
    }

    /**
     * 拼接url 返回时间和路程 查询轨迹信息
     *
     * @param tid
     * @param startTime
     * @param endTime
     */
    public ResponseResult<TrsearchResponse> traceSearch(String tid, Long startTime, Long endTime) {
        StringBuilder url = new StringBuilder();
        //1677372930990&endtime=1677391931000
        url.append(AMapConfigConstant.TERMINAL_TRAROUND_URL);
        url.append("?");
        url.append("key=" + amapKey);
        url.append("&");
        url.append("sid=" + amapSid);
        url.append("&");
        url.append("tid=" + tid);
        url.append("&");
        url.append("starttime=" + startTime);
        url.append("&");
        url.append("endtime=" + endTime);
        log.info("查询轨迹信息的结果请求：" + url.toString());
        ResponseEntity<String> stringResponseEntity = restTemplate.getForEntity(url.toString(), String.class);
        log.info("查询轨迹信息的结果响应：" + stringResponseEntity.getBody());
        // 解析获得的数据
        /**
         * {
         *     "data": {
         *         "counts": 1,
         *         "tracks": [
         *             {
         *                 "counts": 9,
         *                 "degradedParams": {},
         *                 "distance": 2016,米
         *                 "endPoint": {
         *                     "locatetime": 1677380931000,
         *                     "location": "116.333465,39.907328"
         *                 },
         *                 "points": [      { }    ],
         *                 "startPoint": {
         *                 },
         *                 "time": 9000010,毫秒
         *                 "trid": 380
         *             }
         *         ]
         *     },
         *     "errcode": 10000,
         *     "errdetail": null,
         *     "errmsg": "OK"
         * }
         */
        JSONObject result = JSONObject.fromObject(stringResponseEntity.getBody());
        JSONObject data = result.getJSONObject("data");
        int counts = data.getInt("counts");
        if (counts == 0) {
            return ResponseResult.fail("");
        }
        JSONArray tracks = data.getJSONArray("tracks");
        long driverMile = 0L;
        long driverTime = 0L;
        for (int i = 0; i < tracks.size(); i++) {
            JSONObject tracksJSONObject = tracks.getJSONObject(i);

            long distance = tracksJSONObject.getLong("distance");
            driverMile += distance;

            long time = tracksJSONObject.getLong("time");
            time = time / (1000 * 60);//s->min
            driverTime += time;
        }
        TrsearchResponse trsearchResponse = new TrsearchResponse();
        trsearchResponse.setDriverMile(driverMile);
        trsearchResponse.setDriverTime(driverTime);
        return ResponseResult.success(trsearchResponse);

    }
}
